<template>
    <el-dialog v-model="dialogVisible" title="标签管理" width="500px" :close-on-click-modal="false">
        <div class="tag-manage-content">
            <div class="tag-add">
                <el-input v-model="newTagName" placeholder="输入标签名称" @keyup.enter="handleAddTag">
                    <template #append>
                        <el-button @click="handleAddTag">添加</el-button>
                    </template>
                </el-input>
            </div>

            <div class="tag-list">
                <el-empty v-if="!tags.length" description="暂无标签" />
                <template v-else>
                    <div v-for="tag in tags" :key="tag.id" class="tag-item">
                        <template v-if="editingTagId === tag.id">
                            <el-input v-model="editingTagName" size="small" @keyup.enter="handleSaveTag(tag)"
                                @blur="handleSaveTag(tag)" />
                        </template>
                        <template v-else>
                            <span class="tag-name" @dblclick="startEdit(tag)">
                                {{ tag.name }}
                                <span class="tag-count">({{ tag.count || 0 }})</span>
                            </span>
                        </template>
                        <div class="tag-actions">
                            <el-button type="primary" link @click="startEdit(tag)" v-if="editingTagId !== tag.id">
                                编辑
                            </el-button>
                            <el-button type="danger" link @click="handleDeleteTag(tag)">
                                删除
                            </el-button>
                        </div>
                    </div>
                </template>
            </div>
        </div>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible = false">关闭</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, defineProps, defineEmits, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useEmojiStore } from '../stores/emoji'

const props = defineProps({
    modelValue: Boolean
})

const emit = defineEmits(['update:modelValue', 'tag-updated'])
const emojiStore = useEmojiStore()

const dialogVisible = ref(false)
const newTagName = ref('')
const editingTagId = ref(null)
const editingTagName = ref('')
const tags = ref([])

// 监听对话框显示状态
watch(() => props.modelValue, (val) => {
    dialogVisible.value = val
    if (val) {
        loadTags()
    }
})

watch(() => dialogVisible.value, (val) => {
    emit('update:modelValue', val)
    if (!val) {
        newTagName.value = ''
        editingTagId.value = null
        editingTagName.value = ''
    }
})

// 加载标签列表
const loadTags = async () => {
    try {
        tags.value = await emojiStore.getAllTags()
    } catch (error) {
        console.error('加载标签失败:', error)
        ElMessage.error('加载标签失败')
    }
}

// 添加标签
const handleAddTag = async () => {
    if (!newTagName.value.trim()) {
        ElMessage.warning('请输入标签名称')
        return
    }

    try {
        await emojiStore.addTag(newTagName.value.trim())
        ElMessage.success('添加标签成功')
        newTagName.value = ''
        await loadTags()
        emit('tag-updated')
    } catch (error) {
        console.error('添加标签失败:', error)
        ElMessage.error('添加标签失败')
    }
}

// 开始编辑标签
const startEdit = (tag) => {
    editingTagId.value = tag.id
    editingTagName.value = tag.name
}

// 保存编辑后的标签
const handleSaveTag = async (tag) => {
    if (!editingTagName.value.trim()) {
        ElMessage.warning('标签名称不能为空')
        editingTagName.value = tag.name
        editingTagId.value = null
        return
    }

    try {
        await emojiStore.updateTag(tag.id, editingTagName.value.trim())
        ElMessage.success('更新标签成功')
        editingTagId.value = null
        editingTagName.value = ''
        await loadTags()
        emit('tag-updated')
    } catch (error) {
        console.error('更新标签失败:', error)
        ElMessage.error('更新标签失败')
    }
}

// 删除标签
const handleDeleteTag = async (tag) => {
    try {
        await ElMessageBox.confirm(
            '确定要删除这个标签吗？删除后不可恢复。',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )

        await emojiStore.deleteTag(tag.id)
        ElMessage.success('删除标签成功')
        await loadTags()
        emit('tag-updated')
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除标签失败:', error)
            ElMessage.error('删除标签失败: ' + error.message)
        }
    }
}
</script>

<style lang="scss" scoped>
.tag-manage-content {
    .tag-add {
        margin-bottom: 20px;
    }

    .tag-list {
        max-height: 400px;
        overflow-y: auto;

        .tag-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 8px 0;
            border-bottom: 1px solid #ebeef5;

            &:last-child {
                border-bottom: none;
            }

            .tag-name {
                font-size: 14px;
                color: #303133;
                cursor: pointer;

                .tag-count {
                    color: #909399;
                    font-size: 12px;
                    margin-left: 4px;
                }
            }

            .tag-actions {
                display: flex;
                gap: 8px;
            }
        }
    }
}
</style>